package com.github.llyb120.tools.ctrl;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.github.llyb120.json.Obj;
import com.github.llyb120.tools.service.GoogleBarCodeUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.github.llyb120.json.Json.a;
import static com.github.llyb120.json.Json.o;

@RequestMapping("/api/tools/qrcode-maker")
@RestController
public class QRMakerController {

    @RequestMapping("make")
    public Object make(
            @RequestParam Map body,
            MultipartFile file
    ) throws IOException {
        Obj obj = o(body);
        String split = obj.ss("split");
        String[] code1 = obj.ss("code1").split(",");
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream(), 0);
        List result = new ArrayList();
        //暂时只用一个sheet
        for (int i = 0; i < 1; i++) {
            reader.setSheet(i);
            List<List<Object>> lines = reader.read(obj.ii("jumpRows"));
            result = (List) lines.parallelStream()
                    .map(line -> {
                        List<String> items = line
                                .stream()
                                .map(e -> String.valueOf(e))
                                .collect(Collectors.toList());
                        //只保留需要的
                        String code = Arrays.stream(code1)
                                .map(e -> items.get(Integer.parseInt(e)))
                                .collect(Collectors.joining(split));
                        return a(items.get(obj.ii("code0")), GoogleBarCodeUtils.getBarCode(items.get(obj.ii("code0"))), code, QrCodeUtil.generateAsBase64(code, new QrConfig(120,120), "jpg"));
                    })
                    .collect(Collectors.toList());
        }
        return result;
    }
}
